import React, { useState, useEffect, useDeferredValue } from "react";

const App = () => {
  const [value, setValue] = useState("");
  const [list, setList] = useState([]);

  // 用count来表示页面被渲染了几次
  const [count, setCount] = useState(0);

  // 将改变的变量作为参数，得到一个副本
  // 如果页面在不卡顿的情况下，不做任何处理的
  // 当页面卡顿了，会等待数据处理完成，再做渲染
  const value2 = useDeferredValue(value);

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  useEffect(() => {
    setCount((v) => v + 1);
    const newArr = [];
    for (let i = 0; i < 10000; i++) {
      newArr.push({ id: i, value: value2 });
    }
    setList(newArr);
  }, [value2]);

  return (
    <>
      <h2>useDeferredValue</h2>
      <p>页面被渲染了{count}次</p>
      <input type="text" value={value} onChange={handleChange} />
      <ul>
        {list.map((item) => (
          <li key={item.id}>{item.value}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
